<script setup>
import { computed, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import UploadFile from '@/components/UploadFile/UploadFile.vue'
import api from '@/api/index.js'
import { getOptions } from '@/utils'
import { phoneRule } from '@/utils/checkRule.js'
import FullEditor from '@/components/FullEditor/FullEditor.vue'

const emits = defineEmits(['close', 'init', 'reload'])
const props = defineProps({
  curRow: {
    type: Object,
    default: () => ({})
  }
})
// 弹窗标题
const title = computed(() => (props.curRow.trainId ? '编辑数据' : '新增数据'))

//培训内容默认模板
const defaultTrainContent = `<p>随着农业生产全程机械化程度大幅度提高，农业机械使用范围和频率逐步提升，因而农机安全生产的压力也越来越大。工作中发现，现阶段农机安全宣传教育仍缺乏系统性，在培训内容、组织实施、师资教材、培训模式等方面函待深入探索，没有形成较好的农机安全宣传教育实效与影响力。化经常性组织开展农机安全宣传教育工作的难度较大。</p>
  <p> 农机安全生产社会性强、涉及面广，农机安全宣传教育工作是农机安全生产的根本需要，是搞好农机安全生产的基础，是提高农机驾驶操作人员遵纪守法意识，贯彻落实“安全第一、预防为主、综合治理”方针，提级看待“隐患即事故”，最大限度预防和减少农机事故，保障人民群众生命财产安全的重要举措。</p>`

// 表单数据
const formData = ref({
  trainId: '',
  trainTitle: '',
  trainType: '',
  trainImage: '',
  contactUser: '',
  contactPhone: '',
  userName: '',
  userPhone: '',
  trainContent: '',
  startDate: '',
  endDate: '',
  remark: '',
  deleted: '',
  createdTime: '',
  createdBy: '',
  applyCount: '',
  trainStatus: '',
  pickDate: []
})
// 是否显示弹窗
const show = ref(false)
// 同步表格数据到表单数据内
watch(
  () => props.curRow,
  async (val) => {
    if (props.curRow.trainId && show.value) {
      const { resultObject } = await api.getPxglInfo({ id: props.curRow.trainId })
      formData.value = {
        ...formData.value,
        ...val,
        ...resultObject,
        pickDate: [resultObject.startDate, resultObject.endDate]
      }
    } else {
      formData.value = {
        trainId: '',
        trainTitle: '',
        trainType: '',
        trainImage: '',
        contactUser: '',
        contactPhone: '',
        userName: '',
        userPhone: '',
        trainContent: defaultTrainContent,
        startDate: '',
        endDate: '',
        remark: '',
        deleted: '',
        createdTime: '',
        createdBy: '',
        applyCount: '',
        trainStatus: '',
        pickDate: []
      }
    }
  },
  { deep: true, immediate: true }
)
// 弹窗显示状态切换时触发
const afterOpenChange = (bool) => {
  if (!bool) {
    formData.value = {
      trainId: '',
      trainTitle: '',
      trainType: '',
      trainImage: '',
      contactUser: '',
      contactPhone: '',
      userName: '',
      userPhone: '',
      trainContent: defaultTrainContent,
      startDate: '',
      endDate: '',
      remark: '',
      deleted: '',
      createdTime: '',
      createdBy: '',
      applyCount: '',
      trainStatus: '',
      pickDate: []
    }
    emits('close')
  }
}
// 提交按钮loading状态
const submitLoading = ref(false)
// 编辑数据
const emitItem = async (info) => {
  try {
    submitLoading.value = true
    let params = {
      ...formData.value,
      ...info,
      startDate: formData.value?.pickDate?.[0] || '',
      endDate: formData.value?.pickDate?.[1] || ''
    }
    await api.editPxgl(params)
    message.success('编辑成功')
    show.value = false
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
    emits('reload')
  } catch (error) {
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
  }
}
// 新增数据
const addItem = async (info) => {
  try {
    submitLoading.value = true
    let params = {
      ...formData.value,
      ...info,
      startDate: formData.value?.pickDate?.[0] || '',
      endDate: formData.value?.pickDate?.[1] || ''
    }
    await api.addPxgl(params)
    message.success('新增成功')
    show.value = false
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
    emits('init')
  } catch (error) {
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
  }
}
// 表单提交，验证通过了
const onFinish = (values) => {
  if (formData.value.trainId) {
    emitItem(values)
  } else {
    addItem(values)
  }
}
// 验证失败
const onFinishFailed = (errorInfo) => {
  console.log('Failed:', errorInfo)
}
// 打开弹窗
const open = () => {
  show.value = true
}
// 表单节点
const formRef = ref()
// 提交表单
const submit = () => {
  formRef.value.validateFields().then(onFinish).catch(onFinishFailed)
}
defineExpose({ open })
</script>

<template>
  <a-drawer
    :maskClosable="false"
    :closable="false"
    destroyOnClose
    v-model:open="show"
    class="custom-class"
    root-class-name="root-class-name"
    width="1300px"
    :title="title"
    placement="right"
    @after-open-change="afterOpenChange"
  >
    <a-form
      ref="formRef"
      :model="formData"
      layout="vertical"
      autocomplete="off"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
    >
      <a-form-item
        label="培训标题"
        name="trainTitle"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-input v-model:value="formData.trainTitle" allowClear />
      </a-form-item>
      <a-form-item
        label="培训类型"
        name="trainType"
        :rules="[{ required: true, message: '请选择' }]"
      >
        <a-select
          v-model:value="formData.trainType"
          :options="getOptions('train_type')"
          allowClear
          :fieldNames="{ label: 'constLabel', value: 'constValue' }"
        />
      </a-form-item>
      <a-form-item
        label="培训图片"
        name="trainImage"
        :rules="[{ required: true, message: '请上传' }]"
      >
        <a-form-item-rest>
          <UploadFile v-model="formData.trainImage" :limit="1" />
        </a-form-item-rest>
      </a-form-item>
      <a-form-item
        label="联系人"
        name="contactUser"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-input v-model:value="formData.contactUser" allowClear />
      </a-form-item>
      <a-form-item label="联系电话" name="contactPhone" :rules="phoneRule">
        <a-input v-model:value="formData.contactPhone" allowClear />
      </a-form-item>
      <a-form-item
        label="培训状态"
        name="trainStatus"
        :rules="[{ required: true, message: '请选择' }]"
      >
        <a-select
          v-model:value="formData.trainStatus"
          :options="getOptions('train_status')"
          allowClear
          :fieldNames="{ label: 'constLabel', value: 'constValue' }"
        />
      </a-form-item>
      <a-form-item
        label="培训内容"
        name="trainContent"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-form-item-rest>
          <FullEditor v-model="formData.trainContent" />
        </a-form-item-rest>
      </a-form-item>
      <a-form-item
        label="培训时间"
        name="pickDate"
        :rules="[{ required: true, message: '请选择' }]"
      >
        <a-range-picker
          v-model:value="formData.pickDate"
          valueFormat="YYYY-MM-DD"
          format="YYYY-MM-DD"
        />
      </a-form-item>
      <a-form-item label="备注" name="remark">
        <a-input v-model:value="formData.remark" allowClear />
      </a-form-item>
    </a-form>
    <template #footer>
      <div style="display: flex; gap: 5px">
        <a-button type="primary" html-type="submit" @click="submit" :loading="submitLoading"
          >提交</a-button
        >
        <a-button type="primary" ghost @click="show = false">取消</a-button>
      </div>
    </template>
  </a-drawer>
</template>
